package com.JingYan.global;

import cn.hutool.core.lang.Validator;

import com.JingYan.domain.AjaxResult;
import com.JingYan.exception.BaseException;
import com.JingYan.exception.CustomException;
import com.JingYan.exception.XXXException;
import com.JingYan.util.StringUtils;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 全局异常处理器
 *
 * @author itr
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler
{

    /**
     * 基础异常
     */
    @ExceptionHandler(BaseException.class)
    public AjaxResult baseException(BaseException e)
    {
        return AjaxResult.error(e.getMessage());
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(CustomException.class)
    public AjaxResult businessException(CustomException e)
    {
        if (StringUtils.isNull(e.getCode()))
        {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.error(e.getCode(), e.getMessage());
    }
    /**
     * 业务异常
     */
    @ExceptionHandler(XXXException.class)
    public AjaxResult businessException(XXXException e)
    {
        if (StringUtils.isNull(e.getErrorCode()))
        {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.error(e.getErrorCode(), e.getMessage());
    }


    /**
     * 数据库异常
     * @param e
     * @return
     */
    @ExceptionHandler(BadSqlGrammarException.class)
    public AjaxResult handlerSQLException(BadSqlGrammarException e)
    {
        log.error("操作数据库出错 "+e.getMessage(), e);
        return AjaxResult.error("操作数据库出错");
    }


    @ExceptionHandler(NoHandlerFoundException.class)
    public AjaxResult handlerNoFoundException(Exception e)
    {
        log.error(e.getMessage(), e);
        return AjaxResult.error(404, "路径不存在，请检查路径是否正确");
    }

    @ExceptionHandler(AccessDeniedException.class)
    public AjaxResult handleAuthorizationException(AccessDeniedException e)
    {
        log.error(e.getMessage());
        return AjaxResult.error(403, "没有权限，请联系管理员授权");
    }

    @ExceptionHandler(AccountExpiredException.class)
    public AjaxResult handleAccountExpiredException(AccountExpiredException e)
    {
        log.error(e.getMessage(), e);
        return AjaxResult.error(e.getMessage());
    }

    @ExceptionHandler(UsernameNotFoundException.class)
    public AjaxResult handleUsernameNotFoundException(UsernameNotFoundException e)
    {
        log.error(e.getMessage(), e);
        return AjaxResult.error(e.getMessage());
    }


    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public AjaxResult validatedBindException(BindException e)
    {
        log.error(e.getMessage(), e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return AjaxResult.error(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public AjaxResult constraintViolationException(ConstraintViolationException e) {
        log.error(e.getMessage(), e);
        String message = e.getConstraintViolations().iterator().next().getMessage();
        return AjaxResult.error(message);
    }

    /**
     * 自定义验证异常(参数校验异常)
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object validExceptionHandler(MethodArgumentNotValidException e)
    {
        log.error(e.getMessage(), e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return AjaxResult.error(400, message);
    }
    /**
     * 请求参数类型异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public AjaxResult httpMessageNotReadableException(HttpMessageNotReadableException e) {
        Throwable cause = e.getCause();
        if (cause instanceof InvalidFormatException) {
            InvalidFormatException ife = (InvalidFormatException) cause;
            Object value = ife.getValue();
            List<JsonMappingException.Reference> path = ife.getPath();
            String getFieldNames = path.stream().map(
                    JsonMappingException.Reference::getFieldName
            ).collect(Collectors.joining(","));
            return AjaxResult.error("字段: " + getFieldNames + " 请求类型有误,错误的内容: " + value.toString());
        }
        return AjaxResult.error("请求参数有误");
    }


    @ExceptionHandler(IllegalArgumentException.class)
    public AjaxResult illegalArgumentException(IllegalArgumentException e)
    {
        return AjaxResult.error(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception e)
    {
        return handlerOtherException(e);
    }

    public AjaxResult handlerOtherException( Exception e ){
        String message = e.getMessage();
        log.error(message, e);
        if (Validator.hasChinese(message)) {
            return AjaxResult.error(message);
        }else {
            return AjaxResult.error("系统异常,请联系管理员");
        }




    }

}
